/*
 * Copyright (C) 2021 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.example.ventilation.code.fragment.DeviceGroup.Detail.DetailTabs;

import android.graphics.Color;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.ventilation.R;
import com.example.ventilation.base.BaseFragment;
import com.example.ventilation.code.common.model.WindInfoEntity;
import com.example.ventilation.code.fragment.DeviceGroup.Detail.Adapter.ItemTabRealtimeAdapter;
import com.example.ventilation.code.utils.GsonTools;
import com.example.ventilation.code.utils.SharePrefrenceUtil;
import com.example.ventilation.code.utils.WebSocket.WebSocketManager;
import com.example.ventilation.code.utils.WebSocket.WsManager1;
import com.example.ventilation.code.utils.WebSocket.WsStatusListener;
import com.example.ventilation.widget.dashbroad.ClockView_AirVolume;
import com.example.ventilation.widget.dashbroad.ClockView_WindSpeed;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.widget.actionbar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Response;
import okio.ByteString;

import static com.example.ventilation.code.utils.WebSocket.WsStatus.DISCONNECTED;

/**
 * Fragment_Tab_WindRealtime
 * 测风装置 - 单击item - 实时数据
 * @author gehj
 * @time 2/4/21 2:49 PM
 */

public class Fragment_Tab_WindRealtime extends BaseFragment {
    private static final String TAG = "Fragment_Tab_WindRealti";
    @BindView(R.id.refreshLayout_tab_windrealtime)
    SmartRefreshLayout mRefreshLayout;

    @BindView(R.id.clockView_WindSpeed_V1)
    ClockView_WindSpeed mClockViewWindSpeedV1;

    @BindView(R.id.clockView_WindSpeed_V2)
    ClockView_WindSpeed mClockViewWindSpeedV2;

    @BindView(R.id.clockView_WindSpeed_V3)
    ClockView_WindSpeed mClockViewWindSpeedV3;

    @BindView(R.id.tv_realtime_loction)
     TextView mTvRealtimeLoction;

    @BindView(R.id.tv_cross_sectional_area)
     TextView mTvCrossSectionalArea;

    @BindView(R.id.tv_communication_status)
     TextView mTvCommunicationStatus;

    @BindView(R.id.rlv_realtime)
     RecyclerView mRlvRealtime;

    @BindView(R.id.clockView_WindSpeed_Va)
     ClockView_WindSpeed mClockViewWindSpeedVa;
    @BindView(R.id.clockView_AirVolum)
     ClockView_AirVolume mClockViewAirVolum;

    @BindView(R.id.img_tab_detail_skentch)
     ImageView mImgTabDetailSkentch;

    SharePrefrenceUtil sharePrefrenceUtil;

    WindInfoEntity.WindEntity itemInfo;
    JSONArray monitorList;
    ItemTabRealtimeAdapter adapter;
    List<WindInfoEntity.WindEntity> entityList = new ArrayList<>();

    private WsManager1 wsManager1;
    private JSONObject objparam;

    public static Fragment_Tab_WindRealtime newInstance(WindInfoEntity.WindEntity itemInfo) {
        Fragment_Tab_WindRealtime fragment = new Fragment_Tab_WindRealtime();
        Bundle bundle = new Bundle();
        bundle.putSerializable(OBJECT,itemInfo);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected com.xuexiang.xpage.utils.TitleBar initTitleBar() {
        return  null;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //onCreat时候启动WebSocket
        initData();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment__tab__wind_realtime;
    }

    @Override
    protected void initViews() {
        mTvRealtimeLoction.setText(itemInfo.getStrName());
        mTvCrossSectionalArea.setText(String.valueOf(itemInfo.getfSectArea()));
        if(itemInfo.getNetStatus() != null && itemInfo.getNetStatus()==1) {
            mTvCommunicationStatus.setText( "连接");
            mTvCommunicationStatus.setTextColor(Color.GREEN);
        }else {
            mTvCommunicationStatus.setText("断开");
            mTvCommunicationStatus.setTextColor(Color.RED);
        }

        sharePrefrenceUtil = new SharePrefrenceUtil(getActivity());
        wsManager1.sendMessage(objparam.toString());

        if (getActivity() != null){}
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRlvRealtime.setLayoutManager(linearLayoutManager);
        adapter = new ItemTabRealtimeAdapter(getActivity(),entityList);
        mRlvRealtime.setAdapter(adapter);
    }

    private void initData() {
        Bundle bundle = getArguments();
        itemInfo = (WindInfoEntity.WindEntity) bundle.getSerializable("object");
        //为了不与主界面的wsManger冲突，这里重新new一个wsManger
        wsManager1 = WebSocketManager.newInstance(getActivity());
        wsManager1.setWsStatusListener(wsStatusListener);
        wsManager1.startConnect();
        monitorList = new JSONArray();
        monitorList.put(itemInfo.getnSubStationID());
        objparam = new JSONObject();
        try {
            objparam.put("type", "deviceStatus");
            objparam.put("obj", monitorList);
        } catch (JSONException e) {
            e.printStackTrace();
        }


     }

    @Override
    public void onStart() {
        super.onStart();
        if (wsManager1.getCurrentStatus() == DISCONNECTED ){
            wsManager1.tryReconnect();
            wsManager1.sendMessage(objparam.toString());
        }
    }




    private WsStatusListener wsStatusListener = new WsStatusListener() {
            @Override
            public void onMessage(String text) {
                super.onMessage(text);

                Log.e(TAG, "onMessage: " + text);
                WindInfoEntity.MonitorObj entity =
                        GsonTools.getVo(text, WindInfoEntity.MonitorObj.class);
                if (entity != null && entity.getSuccess()
                        && entity.getObj() != null) {
                    //ws有时候会出现延时等现象，仪表盘与列表在一定概率上会发生ANR，改造为WsManger1，
                    //用子线程发数据
                    Message message = Message.obtain();
                    message.what = 0;
                    message.obj = entity.getObj();
                    handler.sendMessage(message);

                }

            }
        };


    Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what== 0){
                if (getActivity() != null){
                    WindInfoEntity.WindEntity windEntity= (WindInfoEntity.WindEntity) msg.obj;

                    mClockViewWindSpeedV1.
                            setCompleteDegree(getFloat(windEntity.getV1A()));
                    mClockViewWindSpeedV2
                            .setCompleteDegree(getFloat(windEntity.getV2A()));
                    mClockViewWindSpeedV3
                            .setCompleteDegree(getFloat(windEntity.getV3A()));
                    mClockViewWindSpeedVa
                            .setCompleteDegree(getFloat(windEntity.getVa()));
                    mClockViewAirVolum
                            .setCompleteDegree(getFloat(windEntity.getM3()));
                    adapter.addEntity(windEntity);
                }

            }
        }
    };

    private Float getFloat(Double d) {
        return Float.parseFloat(String.valueOf(d));
    }

    @Override
    protected TitleBar initTitle() {
        return null;
    }


    /**
     * onPause的时候关闭websocket
     *流程：返回键--> onPause() --> DeviceWindFragment onStart();
     * wsManager.stopConnect()不能在onStop()中调用因为流程是：
     * 返回键 -->DeviceWindFragment onStart() -->onStop() ws将永远无法启动
     */

    @Override
    public void onPause() {
        super.onPause();
        wsManager1.stopConnect();
    }
}